package org.oneblog.controller;

import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.oneblog.bean.ImageConfiger;
import org.oneblog.data.bean.AlbumView;
import org.oneblog.data.bean.ArticleAlbum;
import org.oneblog.data.bean.ArticleSolr;
import org.oneblog.data.query.AlbumQuery;
import org.oneblog.data.query.ArticleSolrQuery;
import org.oneblog.data.rs.Result;
import org.oneblog.data.service.IArticleSolrService;
import org.oneblog.result.AbstractResult;
import org.oneblog.result.UploadImageResult;
import org.oneblog.service.IAlbumService;
import org.oneblog.service.IArticleService;
import org.oneblog.service.IImageService;
import org.oneblog.view.ArticleView;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.commons.CommonsMultipartFile;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.alibaba.fastjson.JSON;

@Controller("ArticleController")
@RequestMapping("/article")
public class ArticleController extends SessionController {
	//登录界面
    @RequestMapping(value = "/manager")
    public ModelAndView manager(HttpServletRequest request) {
        ModelAndView modelAndView = new ModelAndView("/manager/login");
        
        return modelAndView;
    }
    
    //登录 
    @RequestMapping(value = "/login", method = RequestMethod.POST)
    public String login(HttpServletRequest request,
            HttpServletResponse response, RedirectAttributes attr,
			@RequestParam(value = "account", defaultValue = "", required = true) String account,
			@RequestParam(value = "password", defaultValue = "", required = true) String password) {

    	if(account.equalsIgnoreCase("wjyuian") && password.equalsIgnoreCase("wjyuian9633")) {
    		//登录成功
    		setLoginSession(request, response, account);

    		return "redirect:/article/index";
        } else {
        	attr.addFlashAttribute("loginMessage", "账号密码不匹配。");
            return "redirect:/article/manager";
        }
    }
    
    //登录后首页
    @RequestMapping(value = "/index")
    public ModelAndView index(HttpServletRequest request, HttpServletResponse response,
            @ModelAttribute ArticleSolrQuery query) {
        ModelAndView modelAndView = new ModelAndView("/manager/manager_index");
        
        String sessionToken = getSessionToken(request, response);
        
        System.out.println("sessionToken : " + sessionToken);
        Result<ArticleView> articles = articleService.queryArticles(query);
        request.setAttribute("categoryFacet", articleService.categoryFacet());

        request.setAttribute("articles", articles);

        request.setAttribute("query", query);
        
        return modelAndView;
    }
    
    //管理专辑
    @RequestMapping(value = "/album")
    public ModelAndView album(HttpServletRequest request, HttpServletResponse response,
            @ModelAttribute AlbumQuery query) {
        ModelAndView modelAndView = new ModelAndView("/manager/album_list");
        
        List<AlbumView> albums = albumService.getAlbums(query);
        
        request.setAttribute("albums", albums);
        
        return modelAndView;
    }
    //编辑页面
    @RequestMapping(value = "/albume/{albumId}")
    public ModelAndView editAlbum(HttpServletRequest request, HttpServletResponse response
            , @PathVariable String albumId
            ) {

        ModelAndView modelAndView = new ModelAndView("/manager/album_upsert");
        
        AlbumView album = albumService.detail(albumId);
        
        request.setAttribute("album", album);
        
        return modelAndView;
    }
    
    //删除
    @RequestMapping(value = "/albume/del/{albumId}")
    public ModelAndView deleteAlbum(HttpServletRequest request, HttpServletResponse response
            , @PathVariable String albumId
            ) {

        ModelAndView modelAndView = new ModelAndView("redirect:/article/album");
        
        //删除 
        albumService.deleteAlbum(albumId);
        
        return modelAndView;
    }
    //恢复
    @RequestMapping(value = "/albume/recover/{albumId}")
    public ModelAndView recoverAlbum(HttpServletRequest request, HttpServletResponse response
            , @PathVariable String albumId
            ) {

        ModelAndView modelAndView = new ModelAndView("redirect:/article/album");
        
        albumService.recoverAlbum(albumId);
        
        return modelAndView;
    }
    
    //文章详情
    @RequestMapping(value = "/detail")
    public @ResponseBody ArticleSolr detail(HttpServletRequest request,
    		@RequestParam(value = "atclid", defaultValue = "", required = true) String articleId) {
    	
    	ArticleSolr solr = articleSolrService.getById(articleId);
        
        return solr;
    }
    
    //发布文章页面
    @RequestMapping(value = "/publish")
    public ModelAndView publish(HttpServletRequest request) {
        ModelAndView modelAndView = new ModelAndView("manager/publish");
        
        return modelAndView;
    }
    @RequestMapping(value = "/publishblog", method = {RequestMethod.POST})
    public ModelAndView publishBlog(HttpServletRequest request
            , HttpServletResponse response
            , @ModelAttribute ArticleSolr article
            ) {
        ModelAndView modelAndView = new ModelAndView("manager");
        
        String sessionToken = getSessionToken(request, response);
        System.out.println(sessionToken);
        Long userId = 1L;

        int upsertArticle = articleService.upsertArticle(article, userId);
        
        //发布成功，重定向到管理首页 article/index
        if(upsertArticle > 0) {
            modelAndView = new ModelAndView("redirect:index");
        }
        
        return modelAndView;
    }

    @RequestMapping(value = "uploadImage", method = RequestMethod.POST)
    public @ResponseBody AbstractResult<UploadImageResult> uploadCompanyImage(HttpServletRequest request, HttpServletResponse response,
            @RequestParam(value = "avatarfile", required = true) CommonsMultipartFile fileUpload,
            @RequestParam(value = "avatar_data", required = true) String avatarData
            ) {
        HttpHeaders http = new HttpHeaders();
        http.setContentType(MediaType.TEXT_HTML);
        AbstractResult<UploadImageResult> abstractResult = new AbstractResult<UploadImageResult>();
        try {
            System.out.println(avatarData);
            
            //相对根目录的，相对路径
            String relativePath = imageService.uploadImageWithFixedScale(fileUpload.getInputStream(), convertFromJson(avatarData));

            UploadImageResult imageResult = new UploadImageResult();
            
            String url = getBasePath(request) + "staticsrc/img/" + relativePath;
            
            System.out.println("imgurl : " + url);
            imageResult.setImageFullUrl(url);
            
            abstractResult.setData(imageResult);
            abstractResult.setSuccess(true);
                
            return abstractResult;
        } catch (Exception e) {
            e.printStackTrace();
            return abstractResult;
        }
    }
    
    private ImageConfiger convertFromJson(String jsonString) {
        try {
            return JSON.parseObject(jsonString, ImageConfiger.class);
        } catch (Exception e) {
            return new ImageConfiger();
        }
    }
    
    @RequestMapping(value = "/upsertAlbum", method = {RequestMethod.POST})
    public ModelAndView upsertAlbum(HttpServletRequest request
            , HttpServletResponse response
            , @ModelAttribute ArticleAlbum album
            ) {

        ModelAndView modelAndView = new ModelAndView("redirect:/article/album");
        
//        String sessionToken = getSessionToken(request, response);
//        Long userId = 1L;

        int upsert = albumService.upsert(album);
        
        if(upsert < 1) {
        	System.out.println(JSON.toJSONString(album));
        }
        
        return modelAndView;
    }
    
    //获取文章列表
    @RequestMapping(value = "/listarticles")
    @ResponseBody
    public Object listarticles(HttpServletRequest request, HttpServletResponse response,
            @ModelAttribute ArticleSolrQuery query) {

        Result<ArticleView> articles = articleService.queryArticles(query);
        
        if(articles != null) {
        	List<ArticleView> list = articles.getList();
        	if(!CollectionUtils.isEmpty(list)) {
        		for(ArticleView v : list) {
        			v.setContent("");
        		}
        	}
        }
        
        return articles;
    }
    

    @RequestMapping(value = "/rebuild", method = {RequestMethod.POST})
    public ModelAndView rebuild(HttpServletRequest request
            , HttpServletResponse response
            , @ModelAttribute ArticleSolr article
            ) {
        ModelAndView modelAndView = new ModelAndView("redirect:index");;
        
        articleSolrService.rebuildAll();
        
        return modelAndView;
    }
    
    @Resource(name = "articleService")
    IArticleService articleService;

    @Resource(name = "articleSolrService")
    private IArticleSolrService articleSolrService;
    
    @Resource(name = "imageService")
    private IImageService imageService;
    
    @Resource(name = "albumService")
    private IAlbumService albumService;
}
